package com.lazydong.apiforward.client.framework;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ReflectUtil;
import com.lazydong.apiforward.client.framework.annotation.ChildPage;
import com.lazydong.apiforward.client.framework.annotation.MainPage;
import com.lazydong.apiforward.client.framework.util.PackageScannerUtil;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@SuppressWarnings("all")
public class PageContainer {
    private static final AtomicReference<PageAbility> globalMainPage = new AtomicReference<>();
    private static final List<PageAbility> globalChildPage = new ArrayList<>();

    public static void initialize(String packagePath) {
        List<Class<?>> classes = PackageScannerUtil.findClasses(packagePath);
        List<Class<?>> mainPageList = classes.stream()
                .filter(PageAbility.class::isAssignableFrom)
                .filter(temp -> temp.isAnnotationPresent(MainPage.class))
                .toList();
        if (mainPageList.size() != 1) {
            throw new RuntimeException("只能有一个类实现MainPage注解");
        }
        // 构建主页面
        Class<?> mainPageClass = mainPageList.get(0);
        PageAbility mainPage = (PageAbility) ReflectUtil.newInstance(mainPageClass);
        globalMainPage.set(mainPage);
        mainPage.initConfig();
        Object initConfig = mainPage.loadConfig();
        mainPage.buildPage(null, initConfig);
        ThreadUtil.execAsync(mainPage::afterBuildPage);
        JTabbedPane childJPanel = mainPage.getChildJPanel();
        if (childJPanel == null) {
            return;
        }
        // 构建子页面
        List<Class<?>> childPageClassList = classes.stream()
                .filter(PageAbility.class::isAssignableFrom)
                .filter(temp -> temp.isAnnotationPresent(ChildPage.class))
                .toList();
        childPageClassList.forEach(childPageClass -> {
            PageAbility childPage = (PageAbility) ReflectUtil.newInstance(childPageClass);
            globalChildPage.add(childPage);
        });
        // 排序并构建页面
        globalChildPage.sort(Comparator.comparing(PageAbility::getOrder));

        Dimension size = childJPanel.getSize();
        for (PageAbility pageAbility : globalChildPage) {
            pageAbility.initConfig();
            Object config = pageAbility.loadConfig();
            JPanel jPanel = new JPanel();
            jPanel.setSize(size);
            pageAbility.buildPage(jPanel, config);
            PageInfo pageInfoEnum = pageAbility.getPageInfoEnum();
            childJPanel.add(pageInfoEnum.getTabName(), jPanel);
        }
        childJPanel.setSelectedIndex(0);
        ThreadUtil.execAsync(() -> {
            for (PageAbility pageAbility : globalChildPage) {
                try {
                    pageAbility.afterBuildPage();
                } catch (Exception e) {
                    System.out.println("afterBuildPage 执行异常:" + e.getMessage());
                }
            }
        });
    }

    public static void sendAsyncEvent(PageEvent pageEvent, String text) {
        ThreadUtil.execAsync(() -> {
            try {
                globalMainPage.get().monitorEvent(pageEvent, text);
            } catch (Exception e) {
                System.out.println("afterBuildPage 执行异常:" + e.getMessage());
            }
            globalChildPage.forEach(childPage -> {
                try {
                    childPage.monitorEvent(pageEvent, text);
                } catch (Exception e) {
                    System.out.println("afterBuildPage 执行异常:" + e.getMessage());
                }
            });
        });
    }


    public static void sendEvent(PageEvent pageEvent, String text) {
        globalMainPage.get().monitorEvent(pageEvent, text);
        globalChildPage.forEach(childPage -> childPage.monitorEvent(pageEvent, text));
    }

    public static void afterServiceStart() {
        globalMainPage.get().afterServiceStart();
        globalChildPage.forEach(childPage -> childPage.afterServiceStart());
    }
}
